package com.ruoyi.develop.goodsInvoiceDetail.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.finance.financeAr.service.IFinanceArService;
import com.ruoyi.develop.goodsInvoice.domain.GoodsInvoice;
import com.ruoyi.develop.goodsInvoice.service.IGoodsInvoiceService;
import com.ruoyi.develop.goodsInvoiceApplyDetail.domain.GoodsInvoiceApplyDetail;
import com.ruoyi.develop.goodsInvoiceApplyDetail.service.impl.GoodsInvoiceApplyDetailServiceImpl;
import com.ruoyi.develop.projectBaseInfo.domain.ProjectBaseInfo;
import com.ruoyi.develop.projectBaseInfo.service.IProjectBaseInfoService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.develop.goodsInvoiceDetail.domain.GoodsInvoiceDetail;
import com.ruoyi.develop.goodsInvoiceDetail.service.IGoodsInvoiceDetailService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 核销明细信息管理Controller
 *
 * @author qh
 * @date 2023-01-16
 */
@RestController
@RequestMapping("/goodsInvoiceDetail/goodsInvoiceDetail")
public class GoodsInvoiceDetailController extends BaseController {
    @Autowired
    private IGoodsInvoiceDetailService goodsInvoiceDetailService;
    @Autowired
    private IGoodsInvoiceService goodsInvoiceService;
    @Autowired
    private IProjectBaseInfoService projectBaseInfoService;
    @Autowired
    private GoodsInvoiceApplyDetailServiceImpl goodsInvoiceApplyDetailService;
    @Autowired
    private IFinanceArService financeArService;




    /**
     * 查询核销明细信息管理列表
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsInvoiceDetail:query')")
    @GetMapping("/list")
    public TableDataInfo list(GoodsInvoiceDetail entity) {
        startPage();
        List<GoodsInvoiceDetail> list = goodsInvoiceDetailService.selectList(entity);
        return getDataTable(list);
    }

    @GetMapping("/listMingxi")
    public TableDataInfo listMingxi(GoodsInvoiceDetail entity) {
        startPage();
        List<GoodsInvoiceDetail> list = goodsInvoiceDetailService.selectListMingxi(entity);
        return getDataTable(list);
    }

    /**
     * 导出核销明细信息管理列表
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsInvoiceDetail:export')")
    @Log(title = "核销明细信息管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GoodsInvoiceDetail entity) {
        List<GoodsInvoiceDetail> list = goodsInvoiceDetailService.selectList(entity);
        ExcelUtil<GoodsInvoiceDetail> util = new ExcelUtil<GoodsInvoiceDetail>(GoodsInvoiceDetail.class);
        util.exportExcel(response, list, "核销明细信息管理数据");
    }

    /**
     * 获取核销明细信息管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsInvoiceDetail:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(goodsInvoiceDetailService.selectById(id));
    }

    /**
     * 新增核销明细信息管理
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsInvoiceDetail:add')")
    @Log(title = "核销明细信息管理", businessType = BusinessType.INSERT)
    @PostMapping("/hexiao")
    public AjaxResult hexiao(@RequestBody GoodsInvoiceDetail entity) {
        GoodsInvoice goodsInvoice = goodsInvoiceService.selectById(entity.getInvoiceId());
        if (goodsInvoice == null) {
            return AjaxResult.error("发票不存在");
        }
        if( entity.getPinMoney().compareTo(BigDecimal.ZERO) == 0 ){
            return AjaxResult.error("核销金额不能为0");
        }
        if( entity.getPinMoney().compareTo(goodsInvoice.getPinRemain()) > 0 ){
            return AjaxResult.error("核销金额不能大于发票金额");
        }

        goodsInvoice.setPinMoney(goodsInvoice.getPinMoney().add(entity.getPinMoney()));
        goodsInvoice.setPinRemain(goodsInvoice.getPinRemain().subtract(entity.getPinMoney()));

        entity.setProjectId(goodsInvoice.getProjectId());
        entity.setProjectNo(goodsInvoice.getProjectNo());

        // 判断是否核销完成
        if (goodsInvoice.getPinMoney().compareTo(goodsInvoice.getAmount()) == 0) {
            goodsInvoice.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_YHX);
        }
        if(goodsInvoice.getPinMoney().compareTo(goodsInvoice.getAmount()) < 0){
            goodsInvoice.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_BFHX);
        }

        entity.setCustomerId(goodsInvoice.getCustomerId());
        entity.setCustomerName(goodsInvoice.getCustomerName());
        goodsInvoiceService.update(goodsInvoice);
        goodsInvoiceDetailService.insert(entity);

        // 核销之后 生成应收 回款
        financeArService.addByBackMoney(entity);


        // 如果全部 核销 合并 开票 和不合并 开票
        if(goodsInvoice.getPinRemain().compareTo(BigDecimal.ZERO) == 0){
            GoodsInvoiceApplyDetail goodsInvoiceApplyDetail = new GoodsInvoiceApplyDetail();
            goodsInvoiceApplyDetail.setApplyId(goodsInvoice.getId());
            List<GoodsInvoiceApplyDetail> detailList = goodsInvoiceApplyDetailService.selectList(goodsInvoiceApplyDetail);
            if (detailList != null && !detailList.isEmpty()) {
                for (GoodsInvoiceApplyDetail detail : detailList) {
                    // 更新订单上的 回款金额
                    ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(detail.getProjectId());
                    if (projectBaseInfo != null) {
                        projectBaseInfo.setBackMoney(projectBaseInfo.getBackMoney().add(detail.getAmount()));
                        projectBaseInfo.setRemainMoney(projectBaseInfo.getRemainMoney().subtract(detail.getAmount()));
                        if (projectBaseInfo.getRemainMoney().compareTo(BigDecimal.ZERO) == 0) {
                            projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_YHX);
                            projectBaseInfo.setEndDate(new Date());
                        }
                        if (projectBaseInfo.getRemainMoney().compareTo(BigDecimal.ZERO) > 0) {
                            projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_BFHX);
                        }
                        if (projectBaseInfo.getRemainMoney().compareTo(projectBaseInfo.getContractMoney()) == 0) {
                            projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_WHX);
                        }
                        projectBaseInfoService.update(projectBaseInfo);
                    }
                }
            }
        }else{
            ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(goodsInvoice.getProjectId());
            if (projectBaseInfo != null) {
                projectBaseInfo.setBackMoney(projectBaseInfo.getBackMoney().add(goodsInvoice.getPinMoney()));
                projectBaseInfo.setRemainMoney(projectBaseInfo.getRemainMoney().subtract(goodsInvoice.getPinMoney()));
                if (projectBaseInfo.getRemainMoney().compareTo(BigDecimal.ZERO) == 0) {
                    projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_YHX);
                    projectBaseInfo.setEndDate(new Date());
                }

                if (projectBaseInfo.getRemainMoney().compareTo(BigDecimal.ZERO) > 0) {
                    projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_BFHX);
                }
                if (projectBaseInfo.getRemainMoney().compareTo(projectBaseInfo.getContractMoney()) == 0) {
                    projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_WHX);
                }
                projectBaseInfoService.updateBackMoney(projectBaseInfo);
            }
        }
        return AjaxResult.success(1);
    }


    /**
     * 新增核销明细信息管理
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsInvoiceDetail:add')")
    @Log(title = "核销明细信息管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody GoodsInvoiceDetail entity) {
        GoodsInvoice goodsInvoice = goodsInvoiceService.selectById(entity.getInvoiceId());
        entity.setProjectId(goodsInvoice.getProjectId());
        entity.setProjectNo(goodsInvoice.getProjectNo());
        entity.setProjectName(goodsInvoice.getProjectName());
        goodsInvoiceDetailService.insert(entity);
        GoodsInvoiceDetail projectFeeInfo2 = new GoodsInvoiceDetail();
        projectFeeInfo2.setInvoiceId(entity.getInvoiceId());
        List<GoodsInvoiceDetail> projectFeeInfoList = goodsInvoiceDetailService.selectList(projectFeeInfo2);

        BigDecimal allMoney = BigDecimal.ZERO;
        for (GoodsInvoiceDetail projectFeeInfo1 : projectFeeInfoList) {
            if (projectFeeInfo1.getPinMoney() != null) {
                allMoney = projectFeeInfo1.getPinMoney().add(allMoney);
            }
        }
        goodsInvoice.setPinMoney(allMoney);
        goodsInvoice.setPinRemain(goodsInvoice.getAmountReal().subtract(allMoney));
        goodsInvoiceService.update(goodsInvoice);

        String[] ids = goodsInvoice.getProjectId().split(",");
        for (String id : ids) {
            ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(id);
            if (projectBaseInfo != null) {
                /*if(projectBaseInfo.getContractMoney().compareTo(entity.getPinMoney())>0){
                    projectBaseInfo.setBackMoney(projectBaseInfo.getBackMoney().add(entity.getPinMoney()));
                    projectBaseInfo.setRemainMoney(projectBaseInfo.getRemainMoney().subtract(entity.getPinMoney()));
                }else {
                    projectBaseInfo.setBackMoney(projectBaseInfo.getContractMoney());
                    projectBaseInfo.setRemainMoney(BigDecimal.ZERO);
                }*/
                projectBaseInfo.setBackMoney(projectBaseInfo.getBackMoney().add(entity.getPinMoney()));
                projectBaseInfo.setRemainMoney(projectBaseInfo.getRemainMoney().subtract(entity.getPinMoney()));
                if (projectBaseInfo.getRemainMoney().compareTo(BigDecimal.ZERO) < 0) {
                    projectBaseInfo.setRemainMoney(BigDecimal.ZERO);
                }
                projectBaseInfoService.update(projectBaseInfo);
            }
        }
        goodsInvoiceDetailService.update(entity);
        return null;
    }

    @Log(title = "批量核销明细信息管理", businessType = BusinessType.INSERT)
    @PostMapping("/addPiliang")
    public AjaxResult addPiliang(@RequestBody GoodsInvoiceDetail entity) {
        String[] invoiceIds = entity.getIds();
        for (String invoiceId : invoiceIds) {
            GoodsInvoiceDetail goodsInvoiceDetail = new GoodsInvoiceDetail();
            GoodsInvoice goodsInvoice = goodsInvoiceService.selectById(invoiceId);
            goodsInvoiceDetail.setInvoiceId(invoiceId);
            goodsInvoiceDetail.setProjectId(goodsInvoice.getProjectId());
            goodsInvoiceDetail.setProjectNo(goodsInvoice.getProjectNo());
            goodsInvoiceDetail.setProjectName(goodsInvoice.getProjectName());
            goodsInvoiceDetail.setPinMoney(entity.getPinMoney());
            goodsInvoiceDetail.setPinDate(entity.getPinDate());
            goodsInvoiceDetail.setFiles(entity.getFiles());
            goodsInvoiceDetail.setRemark(entity.getRemark());
            goodsInvoiceDetailService.insert(goodsInvoiceDetail);
            goodsInvoice.setPinMoney(goodsInvoice.getAmount());
            goodsInvoice.setPinRemain(BigDecimal.ZERO);
            goodsInvoice.setFundCallback(BusinessConstants.FUND_YES);
            goodsInvoiceService.update(goodsInvoice);

            String[] ids = goodsInvoice.getProjectId().split(",");
            for (String id : ids) {
                ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(id);
                if (projectBaseInfo != null) {
                /*if(projectBaseInfo.getContractMoney().compareTo(entity.getPinMoney())>0){
                    projectBaseInfo.setBackMoney(projectBaseInfo.getBackMoney().add(entity.getPinMoney()));
                    projectBaseInfo.setRemainMoney(projectBaseInfo.getRemainMoney().subtract(entity.getPinMoney()));
                }else {
                    projectBaseInfo.setBackMoney(projectBaseInfo.getContractMoney());
                    projectBaseInfo.setRemainMoney(BigDecimal.ZERO);
                }*/
                    projectBaseInfo.setBackMoney(projectBaseInfo.getContractMoney());
                    projectBaseInfo.setRemainMoney(BigDecimal.ZERO);
                    projectBaseInfoService.update(projectBaseInfo);
                }
            }
        }
        return null;
    }

    /**
     * 修改核销明细信息管理
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsInvoiceDetail:edit')")
    @Log(title = "核销明细信息管理", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody GoodsInvoiceDetail entity) {
        return toAjax(goodsInvoiceDetailService.update(entity));
    }

    /**
     * 删除核销明细信息管理
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsInvoiceDetail:remove')")
    @Log(title = "核销明细信息管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        goodsInvoiceDetailService.deleteByIds(ids);
        for (String id : ids) {
            GoodsInvoiceDetail projectFeeInfo = goodsInvoiceDetailService.selectById(id);
            if (projectFeeInfo != null) {
                GoodsInvoiceDetail projectFeeInfo2 = new GoodsInvoiceDetail();
                projectFeeInfo2.setInvoiceId(projectFeeInfo.getInvoiceId());
                List<GoodsInvoiceDetail> projectFeeInfoList = goodsInvoiceDetailService.selectList(projectFeeInfo2);
                BigDecimal allMoney = BigDecimal.ZERO;
                for (GoodsInvoiceDetail projectFeeInfo1 : projectFeeInfoList) {
                    if (projectFeeInfo1.getPinMoney() != null) {
                        allMoney = projectFeeInfo1.getPinMoney().add(allMoney);
                    }
                }
                GoodsInvoice goodsInvoice = goodsInvoiceService.selectById(projectFeeInfo.getInvoiceId());
                goodsInvoice.setPinMoney(allMoney);
                goodsInvoice.setPinRemain(goodsInvoice.getAmountReal().subtract(allMoney));
                goodsInvoiceService.update(goodsInvoice);

                ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(goodsInvoice.getProjectId());
                if (projectBaseInfo != null) {
                    projectBaseInfo.setBackMoney(projectBaseInfo.getBackMoney().subtract(projectFeeInfo.getPinMoney()));
                    projectBaseInfo.setRemainMoney(projectBaseInfo.getRemainMoney().add(projectFeeInfo.getPinMoney()));
                    projectBaseInfoService.update(projectBaseInfo);
                }
            }
        }
        return null;
    }


    /**
     * 取消核销
     */
    @GetMapping("/cancelHexiao/{ids}")
    public AjaxResult cancelHexiao(@PathVariable String[] ids) {
        for (String id : ids) {
            GoodsInvoiceDetail invoiceDetail = goodsInvoiceDetailService.selectById(id);
            GoodsInvoice goodsInvoice = goodsInvoiceService.selectById(invoiceDetail.getInvoiceId());
            goodsInvoice.setPinRemain(goodsInvoice.getPinRemain().add(invoiceDetail.getPinMoney()));
            goodsInvoice.setPinMoney(goodsInvoice.getPinMoney().subtract(invoiceDetail.getPinMoney()));
            goodsInvoice.setBackDate(null);

            if (goodsInvoice.getPinRemain().compareTo(goodsInvoice.getAmount()) == 0) {
                goodsInvoice.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_WHX);
            }

            if(goodsInvoice.getPinRemain().compareTo(goodsInvoice.getAmount()) < 0){
                goodsInvoice.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_BFHX);
            }

            goodsInvoiceService.update(goodsInvoice);
            goodsInvoiceDetailService.deleteById(id);
            financeArService.addByBackMoneyCancel(invoiceDetail);

            if(goodsInvoice.getPinMoney().compareTo(BigDecimal.ZERO) == 0){
                GoodsInvoiceApplyDetail goodsInvoiceApplyDetail = new GoodsInvoiceApplyDetail();
                goodsInvoiceApplyDetail.setApplyId(id);
                List<GoodsInvoiceApplyDetail> detailList = goodsInvoiceApplyDetailService.selectList(goodsInvoiceApplyDetail);
                if (detailList != null && !detailList.isEmpty()) {
                    for (GoodsInvoiceApplyDetail detail : detailList) {
                        // 更新订单上的 回款金额
                        ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(detail.getProjectId());
                        if (projectBaseInfo != null) {
                            projectBaseInfo.setBackMoney(projectBaseInfo.getBackMoney().subtract(detail.getAmount()));
                            projectBaseInfo.setRemainMoney(projectBaseInfo.getRemainMoney().add(detail.getAmount()));
                            if (projectBaseInfo.getRemainMoney().compareTo(BigDecimal.ZERO) == 0) {
                                projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_YHX);
                            }
                            if (projectBaseInfo.getRemainMoney().compareTo(BigDecimal.ZERO) > 0) {
                                projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_BFHX);
                            }
                            if (projectBaseInfo.getRemainMoney().compareTo(projectBaseInfo.getContractMoney()) == 0) {
                                projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_YHX);
                            }
                            projectBaseInfo.setEndDate(null);
                            projectBaseInfoService.update(projectBaseInfo);
                        }
                    }
                }
            }

        }
        return AjaxResult.success("批量取消核销成功");
    }
















}
